#import "IosKitPlugin.h"
#import <Photos/Photos.h>

@implementation IosKitPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* channel = [FlutterMethodChannel
                                     methodChannelWithName:@"ios_kit"
                                     binaryMessenger:[registrar messenger]];
    IosKitPlugin* instance = [[IosKitPlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    if ([@"getPlatformVersion" isEqualToString:call.method]) {
        result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    }
    else if([@"isIOS14" isEqualToString:call.method]) {
        if (@available(iOS 14, *)) {
            result(@"true");
        } else {
            result(@"false");
        }
    }
    else if([@"openSetting" isEqualToString:call.method]) {
        [self openSetting];
        result(@"openSetting");
    }
    else if([@"checkStatus" isEqualToString:call.method]) {
        if (@available(iOS 14, *)) {
            // 查询权限
            PHAccessLevel level = PHAccessLevelReadWrite;
            PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatusForAccessLevel:level];
            if (status != PHAuthorizationStatusAuthorized) {
                NSLog(@"non-authorized");
                // 请求权限，需注意 limited 权限尽在 accessLevel 为 readAndWrite 时生效
                [PHPhotoLibrary requestAuthorizationForAccessLevel:level handler:^(PHAuthorizationStatus status) {
                    switch (status) {
                        case PHAuthorizationStatusLimited:
                            NSLog(@"limited");
                            result(@"limited");
                            break;
                        case PHAuthorizationStatusDenied:
                            NSLog(@"denied");
                            result(@"denied");
                            break;
                        case PHAuthorizationStatusAuthorized:
                            NSLog(@"authorized");
                            result(@"authorized");
                            break;
                        default:
                            result(@"non-authorized");
                            break;
                    }
                }];
                
            }else {
                result(@"true");
            }
        } else {
            result(@"false");
        }
    }
    else {
        result(FlutterMethodNotImplemented);
    }
}
- (void)openSetting {
    //注，这里一定要回归的主线程操作UI
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    });
}

@end
